﻿using System;
using System.Linq.Expressions;
using Medora.Model;

namespace Medora.Data
{
    public class SortConstructor<T> : ISortConstructor<T>
        where T : class
    {

        public Expression<Func<T, DateTime>> GetSortExpessionByDateTime(string field)
        {
            MemberExpression body;
            var param = PrepareParameterExpression(field, out body);
            return Expression.Lambda<Func<T, DateTime>>(body, new ParameterExpression[] { param });
        }

        public Expression<Func<T, string>> GetSortExpessionByString(string field)
        {
            MemberExpression body;
            var param = PrepareParameterExpression(field, out body);
            return Expression.Lambda<Func<T, string>>(body, new ParameterExpression[] { param });
        }

        public Expression<Func<T, double>> GetSortExpessionByDouble(string field)
        {
            MemberExpression body;
            var param = PrepareParameterExpression(field, out body);
            return Expression.Lambda<Func<T, double>>(body, new ParameterExpression[] { param });
        }

        public Expression<Func<T, int>> GetSortExpessionByInt(string field)
        {
            MemberExpression body;
            var param = PrepareParameterExpression(field, out body);
            return Expression.Lambda<Func<T, int>>(body, new ParameterExpression[] { param });
        }

        private static ParameterExpression PrepareParameterExpression(string field, out MemberExpression body)
        {
            var type = typeof(T);
            ParameterExpression param = Expression.Parameter(type, field);
            body = Expression.PropertyOrField(param, field);
            return param;
        }
        
    }
}